package com.pig4cloud.pig.ads.gdt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.gdt.service.GdtAdvertiserService;
import com.pig4cloud.pig.ads.gdt.service.GdtAudiencePackageService;
import com.pig4cloud.pig.ads.pig.mapper.gdt.GdtAudiencePackageMapper;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.enums.ToutiaoGdtAudiencePackageFieldsEnum;
import com.pig4cloud.pig.api.gdt.dto.GdtAudiencePackagePageReq;
import com.pig4cloud.pig.api.gdt.entity.GdtAdvertiser;
import com.pig4cloud.pig.api.gdt.entity.GdtAudiencePackage;
import com.pig4cloud.pig.api.gdt.vo.GdtAudiencePackageVo;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

@Log4j2
@Service
@RequiredArgsConstructor
public class GdtAudiencePackageServiceImpl extends ServiceImpl<GdtAudiencePackageMapper, GdtAudiencePackage> implements GdtAudiencePackageService {

	private final GdtAudiencePackageMapper baseMapper;

	private final GdtAccesstokenService gdtAccesstokenService;

	private final AdvService advService;

	private final GdtAdvertiserService gdtAdvertiserService;

	@Override
	public void test() {
		GdtAudiencePackage item = baseMapper.selectById(12);
		System.out.println("");
	}


	@Override
	public R create(GdtAudiencePackage entity) {
		//名称不能重复
		GdtAudiencePackage recordSameName = this.getBaseMapper().selectByName(entity.getTargetingName());
		if (recordSameName!=null)
			return R.failed("名称 不能重复");

		Map<String, Object> reqData = this.entityToMap(entity);

		//数据校验
		R validateResult = this.dataValidate(reqData);
		if (validateResult.getCode() != CommonConstants.SUCCESS)
			return validateResult;

		entity.setCreatedTime(System.currentTimeMillis());
		entity.setIsDeleted("false");
		entity.setCreatedTime(System.currentTimeMillis()/1000);
		entity.setSyncStatus(Short.valueOf("0"));

		if (!SqlHelper.retBool(this.getBaseMapper().insert(entity)))
			return R.failed("插入数据库失败");



		//在头条创建定向包
		R syncStatus = this.createInGdt(entity.getId(), reqData);

		if (syncStatus.getCode() != CommonConstants.SUCCESS)
			return syncStatus;
		else
			return R.ok(null,"添加成功");
	}

	@Override
	public R update(GdtAudiencePackage entity) {
		GdtAudiencePackage recordOld = this.getBaseMapper().selectById(entity.getId());
		if (recordOld == null)
			return R.failed(String.format("定向包[%d]不存在!!!", entity.getId()));

		//名称不能重复
		GdtAudiencePackage recordSameName = this.getBaseMapper().selectByName(entity.getTargetingName());
		if (recordSameName !=null && !recordSameName.getId().equals(entity.getId()))
			return R.failed("名称 不能重复");


		Map<String, Object> reqData = this.entityToMap(entity);
		reqData.put("targeting_id", recordOld.getIdAdplatform());

		//数据校验
		R validateResult = this.dataValidate(reqData);
		if (validateResult.getCode() != CommonConstants.SUCCESS)
			return validateResult;

		if (recordOld.getIdAdplatform() != null){
			R uptResult = this.updateInGdt(reqData, recordOld);
			if (uptResult.getCode() != CommonConstants.SUCCESS)
				return uptResult;
		}

		//2、更新到数据库
		if (!SqlHelper.retBool(baseMapper.updateInfoByPrimaryKey(entity)))
			R.failed("广点通更新成功,本地更新失败!!!");

		return R.ok(null, "更新成功");
	}

	@Override
	public <E extends IPage<GdtAudiencePackage>> IPage<GdtAudiencePackageVo> pagedAudiencePackage(Page page,GdtAudiencePackagePageReq req) {

		//PigUser usr = SecurityUtils.getUser();
		Integer id = SecurityUtils.getUser().getId();


		QueryWrapper<GdtAudiencePackage> wrapper = new QueryWrapper<>();
		wrapper.orderByDesc("id");
		wrapper.eq("is_deleted","false");

		//只获取当前有权限的数据
		List<GdtAdvertiser> advers = gdtAdvertiserService.curUserAdvers();
		if (advers != null && advers.size()>0){
			List<String> strAdvers = advers.stream().map(adver -> adver.getAccountId()).collect(Collectors.toList());
			wrapper.in("account_id", strAdvers);
		}else{
			wrapper.eq("account_id", "-1");
		}

/*		if (adAccountMap.size()>0){
			wrapper.in("advertiser_id", adAccountMap.keySet());
		}else{
			wrapper.eq("advertiser_id", "-1");
		}*/
		List<String> advers01 = new ArrayList<>();

		if (req.getAdvertiserIds() != null && req.getAdvertiserIds().length>0){
			advers01.addAll(Arrays.asList(req.getAdvertiserIds()));
		}
		if (req.getAccountIds() != null && req.getAccountIds().length>0){
			advers01.addAll(Arrays.asList(req.getAccountIds()));
		}
		if (advers01.size()>0)
			wrapper.in("account_id", advers01);

		if (req.getSyncStatus() != null){
			wrapper.eq("sync_status", req.getSyncStatus());

			if (req.getSyncStatus().equals(Short.valueOf("1")))
				wrapper.isNotNull("id_adplatform");
		}
		IPage<GdtAudiencePackage> result = this.getBaseMapper().selectPage(page, wrapper);

		List<GdtAudiencePackageVo> voList = new ArrayList<>();
		for (GdtAudiencePackage item : result.getRecords()){
			GdtAudiencePackageVo itemVo = new GdtAudiencePackageVo();
			BeanUtils.copyProperties(item, itemVo);

			//获取 advertiser name
			//itemVo.setAdvertiserName(adAccountMap.get(item.getAdvertiserId()));

			//统计 绑定计划个数
			//int adPlanCount = adPlanMapper.countByAudienceId(Long.valueOf(item.getId()));
			//itemVo.setAdPlanCount(adPlanCount);
			itemVo.setAdPlanCount(0);

			voList.add(itemVo);
		}

		IPage<GdtAudiencePackageVo> voPage = new Page<GdtAudiencePackageVo>(result.getCurrent(),result.getSize(),result.getTotal());
		voPage.setRecords(voList);
		return voPage;
	}

	@Override
	public GdtAudiencePackage detail(Integer id) {
		GdtAudiencePackage record = this.getBaseMapper().selectById(id);

		if (record.getIsDeleted().equals("true"))
			return null;

		return record;
	}

	@Override
	public R remove(Integer id) {

		GdtAudiencePackage record = this.getBaseMapper().selectById(id);
		if (record == null)
			return R.failed(String.format("定向包[%d]不存在!!!", id));

		R uptResult = this.removeInGdt(record);
		if (uptResult.getCode() != CommonConstants.SUCCESS && uptResult.getCode() != 130101)
			return uptResult;

		//2、更新到数据库
		record.setIsDeleted("true");
		if (!SqlHelper.retBool(baseMapper.updateByPrimaryKeySelective(record)))
			return R.failed("广点通删除成功,本地删除失败!!!");
		else
			return R.ok(null, "删除成功");
	}

//

	//---------------------------------------------------------

	private R createInGdt(Long id,Map<String, Object> reqData){
		//数据校验
		R validateResult = this.dataValidate(reqData);
		if (validateResult.getCode() != CommonConstants.SUCCESS)
			return validateResult;

		//调用 三方接口
		if (reqData.get("account_id") == null || StringUtils.isBlank(String.valueOf(reqData.get("account_id"))))
			return R.failed("未提供广告账户");
		String resultStr = OEHttpUtils.doPost("https://api.e.qq.com/v1.3/targetings/" + "add" + getUrlTail(String.valueOf(reqData.get("account_id"))), reqData, null);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("第三方创建失败:resultStr is blank");

		JSONObject respObj = JSON.parseObject(resultStr);
		if (!respObj.getInteger("code").equals(0)){	//同步失败
			GdtAudiencePackage tmp = new GdtAudiencePackage();
			tmp.setId(id);
			tmp.setSyncStatus(Short.valueOf("2"));

			baseMapper.updateByPrimaryKeySelective(tmp);		//更新失败状态到db

			String msg = respObj.getString("message_cn");
			return R.failed("第三方创建失败:" + chineseMsg(msg));
		}

		//若同步成功	跟更新状态到数据库
		JSONObject dataObj = respObj.getJSONObject("data");

		GdtAudiencePackage tmp = new GdtAudiencePackage();
		tmp.setId(id);
		tmp.setIdAdplatform(dataObj.getLong("targeting_id"));
		tmp.setSyncStatus(Short.valueOf("1"));		//同步成功
		if (!SqlHelper.retBool(baseMapper.updateByPrimaryKeySelective(tmp)))
			return R.failed("第三方创建成功后，本地更新状态失败");

		return R.ok(dataObj,"第三方创建成功");
	}

	private R updateInGdt(Map<String, Object> reqData, GdtAudiencePackage eOld){
		R validateResult = this.dataValidate(reqData);
		if (validateResult.getCode() != CommonConstants.SUCCESS)
			return validateResult;

		if (reqData.get("account_id") == null || StringUtils.isBlank(String.valueOf(reqData.get("account_id"))))
			return R.failed("未提供广告账户");
		String resultStr = OEHttpUtils.doPost("https://api.e.qq.com/v1.3/targetings/" + "update" + getUrlTail(String.valueOf(reqData.get("account_id"))), reqData, null);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("第三方更新失败:resultStr is null");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			String msg = obj.getString("message_cn");
			return R.failed("第三方更新失败:" + chineseMsg(msg));
		}

		//若同步成功	跟更新状态到数据库
		return R.ok(null,"第三方更新成功");
	}

	private R removeInGdt(GdtAudiencePackage entity){
		if (entity.getIdAdplatform() == null){
			R rst = R.failed(String.format("定向包[%d]在广点通不存在!!!", entity.getId()));;
			rst.setCode(130101);
			return rst;
		}

		Map<String, Object> reqData = new HashMap<>();
		reqData.put("account_id",entity.getAccountId());
		reqData.put("targeting_id",entity.getIdAdplatform());

		if (entity.getAccountId() == null)
			return R.failed("未提供广告账户");
		String resultStr = OEHttpUtils.doPost("https://api.e.qq.com/v1.3/targetings/" + "delete" + getUrlTail(String.valueOf(entity.getAccountId())) , reqData, null);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("第三方删失败:resultStr is null");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("第三方删失败:" + obj.getString("message_cn"));
		}

		//若同步成功	跟更新状态到数据库
		return R.ok(null,"第三方删成功");
	}



	//---------------------------------------------------------


	//todo_kyle  完善更多细节
	private Map<String, Object> entityToMap(GdtAudiencePackage entity) {
		Map<String, Object> reqData = new HashMap<>();
		JSONObject targeting =  new JSONObject();
		reqData.put("targeting",targeting);

		if (entity.getAccountId() != null){
			reqData.put("account_id", String.valueOf(entity.getAccountId()));   			//entity.getAccountId()
		}
		if (StringUtils.isNotBlank(entity.getTargetingName())){
			reqData.put("targeting_name", entity.getTargetingName());		//entity.getTargetingName()
		}
		if (StringUtils.isNotBlank(entity.getDescription())){
			reqData.put("description", entity.getDescription());
		}

/*		if (StringUtils.isNotBlank(entity.getGender())){
			targeting.put("gender", JSON.parseArray(entity.getGender()));
		}else{
			targeting.put("gender", null);
		}*/

		addArrParam(targeting, "age"                                 , entity.getAge()  );
		addArrParam(targeting, "gender"                              , entity.getGender()  );
		addArrParam(targeting, "education"                           , entity.getEducation()  );
		addArrParam(targeting, "marital_status"                      , entity.getMaritalStatus()  );
		addArrParam(targeting, "working_status"                      , entity.getWorkingStatus()  );
		addArrParam(targeting, "user_os"                             , entity.getUserOs()  );
		addArrParam(targeting, "new_device"                          , entity.getNewDevice()  );
		addArrParam(targeting, "device_price"                        , entity.getDevicePrice()  );
		addArrParam(targeting, "network_type"                        , entity.getNetworkType()  );
		addArrParam(targeting, "network_operator"                    , entity.getNetworkOperator()  );
		addArrParam(targeting, "network_scene"                       , entity.getNetworkScene()  );
		addArrParam(targeting, "dressing_index"                      , entity.getDressingIndex()  );
		addArrParam(targeting, "uv_index"                            , entity.getUvIndex()  );
		addArrParam(targeting, "makeup_index"                        , entity.getMakeupIndex()  );
		addArrParam(targeting, "climate"                             , entity.getClimate()  );
		addArrParam(targeting, "temperature"                         , entity.getTemperature()  );
		addArrParam(targeting, "air_quality_index"                   , entity.getAirQualityIndex()  );
		addArrParam(targeting, "app_install_status"                  , entity.getAppInstallStatus()  );
		addArrParam(targeting, "consumption_status"                  , entity.getConsumptionStatus()  );
		addArrParam(targeting, "game_consumption_level"              , entity.getGameConsumptionLevel()  );
		addArrParam(targeting, "residential_community_price"         , entity.getResidentialCommunityPrice()  );
		addArrParam(targeting, "financial_situation"                 , entity.getFinancialSituation()  );
		addArrParam(targeting, "consumption_type"                    , entity.getConsumptionType()  );
		addArrParam(targeting, "custom_audience"                     , entity.getCustomAudience()  );
		addArrParam(targeting, "excluded_custom_audience"            , entity.getExcludedCustomAudience()  );
		addArrParam(targeting, "mini_game_qq_status"                 , entity.getMiniGameQqStatus()  );
		addArrParam(targeting, "wechat_official_account_category"    , entity.getWechatOfficialAccountCategory()  );
		addArrParam(targeting, "mobile_union_category"               , entity.getMobileUnionCategory()  );
		addArrParam(targeting, "business_interest"                   , entity.getBusinessInterest()  );
		addArrParam(targeting, "app_behavior"                        , entity.getAppBehavior()  );
		addArrParam(targeting, "paid_user"                           , entity.getPaidUser()  );
		addArrParam(targeting, "deprecated_custom_audience"          , entity.getDeprecatedCustomAudience()  );
		addArrParam(targeting, "deprecated_excluded_custom_audience" , entity.getDeprecatedExcludedCustomAudience()  );
		addArrParam(targeting, "deprecated_region"                   , entity.getDeprecatedRegion()  );

		addObjParam(targeting,      "geo_location"                   , entity.getGeoLocation());
		addObjParam(targeting,      "device_brand_model"             , entity.getDeviceBrandModel());
		addObjParam(targeting,      "behavior_or_interest"           , entity.getBehaviorOrInterest());
		addObjParam(targeting,      "wechat_ad_behavior"             , entity.getWechatAdBehavior());
		addObjParam(targeting,      "keyword"                        , entity.getKeyword());

		return reqData;
	}

	private void addArrParam(JSONObject targeting,String name,String value){
		if (StringUtils.isNotBlank(value)){
			JSONArray valueArr = JSON.parseArray(value);
			if (valueArr != null)
				targeting.put(name, valueArr);
		}
	}

	private void addObjParam(JSONObject targeting,String name,String value){
		if (StringUtils.isNotBlank(value)){
			targeting.put(name, JSON.parseObject(value));
		}
	}

	private R dataValidate(Map<String, Object> reqData){
		JSONObject json = JSON.parseObject(JSON.toJSONString(reqData));

		if (StringUtils.isBlank("account_id"))
			return R.failed("未提供 广告账户");

		//必需字段 非空检验

		//检验 定向包名称
		String targatingName = json.getString("targeting_name");
		if (StringUtils.isBlank(targatingName)){
			return R.failed("未提供定向包名");
		}
		else{
			int namelen = getLength(targatingName);
			if (namelen <1 || namelen >120){
				return R.failed("定向名称 长度最小 1 字节，长度最大 120 字节");
			}
		}

		//检查描述的长度
		if (StringUtils.isNotBlank(json.getString("description"))){
			int descriptionLen = getLength(json.getString("description"));
			if (descriptionLen > 250){
				return R.failed("定向包描述 长度最小 0 字节，长度最大 250 字节");
			}
		}


		JSONObject targeting = json.getJSONObject("targeting");

		if (targeting.getJSONArray("age") != null){
			JSONArray ages = targeting.getJSONArray("age");
			if (ages.size() != 1){
				return R.failed("年龄 数组长度为 1");
			}

			JSONObject age = ages.getJSONObject(0);
			if (StringUtils.isBlank(age.getString("min")))
				return R.failed("缺少最小年龄");
			if (StringUtils.isBlank(age.getString("max")))
				return R.failed("缺少最大年龄");

			if (age.getInteger("min") > age.getInteger("max"))
				return R.failed("最小年龄不能大于最大年龄");
		}

		if (targeting.getJSONArray("gender") != null
				&& targeting.getJSONArray("gender").size()>1){
			return R.failed("性别 数组长度为 1");
		}

		if (targeting.getJSONArray("education") != null
				&& (targeting.getJSONArray("education").size()< 1 || targeting.getJSONArray("education").size()>100)){
			return R.failed("学历 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("marital_status") != null
				&& (targeting.getJSONArray("marital_status").size()< 1 ||
				    targeting.getJSONArray("marital_status").size()>100)){
			return R.failed("婚恋育儿状态 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("working_status") != null
				&& (targeting.getJSONArray("working_status").size()< 1 ||
				targeting.getJSONArray("working_status").size()>100)){
			return R.failed("工作状态 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("user_os") != null
				&& (targeting.getJSONArray("user_os").size()< 1 ||
				targeting.getJSONArray("user_os").size()>100)){
			return R.failed("操作系统版本 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("new_device") != null
				&& (targeting.getJSONArray("new_device").size()< 1 ||
				targeting.getJSONArray("new_device").size()>100)){
			return R.failed("新设备 最小长度 1，最大长度 100");
		}


		if (targeting.getJSONArray("user_os") != null
				&& (targeting.getJSONArray("user_os").size()< 1 ||
				targeting.getJSONArray("user_os").size()>100)){
			return R.failed("操作系统版本 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("temperature") != null){
			JSONArray temperatures = targeting.getJSONArray("temperature");

			if (targeting.getJSONArray("temperature").size() != 1)
				return R.failed("温度 为单选");

			JSONObject temperature = temperatures.getJSONObject(0);
			if (StringUtils.isBlank(temperature.getString("min")))
				return R.failed("缺少最低温度");
			if (StringUtils.isBlank(temperature.getString("max")))
				return R.failed("缺少最高温度");

			if (temperature.getInteger("min") > temperature.getInteger("max"))
				return R.failed("最低温度不能大于最高温度");
		}

		if (targeting.getJSONArray("air_quality_index") != null
				&& targeting.getJSONArray("air_quality_index").size() != 1){
			return R.failed("空气质量指数 为单选");
		}

		if (targeting.getJSONArray("app_install_status") != null
				&& targeting.getJSONArray("app_install_status").size() != 1){
			return R.failed("应用安装选项 为单选");
		}

		if (targeting.getJSONArray("residential_community_price") != null){
			JSONArray arr = targeting.getJSONArray("residential_community_price");
			if (targeting.getJSONArray("residential_community_price").size() != 1)
				return R.failed("居住社区价格 为单选");

			JSONObject price = arr.getJSONObject(0);
			if (StringUtils.isBlank(price.getString("min")))
				return R.failed("居住社区价格 缺少最小价格");
			if (StringUtils.isBlank(price.getString("max")))
				return R.failed("居住社区价格 缺少最大价格");

			if (price.getInteger("min") >= price.getInteger("max"))
				return R.failed("居住社区价格 最小价格不能>=最大价格");
		}

		if (targeting.getJSONArray("custom_audience") != null
				&& (targeting.getJSONArray("custom_audience").size()< 1 ||
				targeting.getJSONArray("custom_audience").size()>200)){
			return R.failed("人群定向 最小长度 1，最大长度 200");
		}

		if (targeting.getJSONArray("excluded_custom_audience") != null
				&& (targeting.getJSONArray("excluded_custom_audience").size()< 1 ||
				targeting.getJSONArray("excluded_custom_audience").size()>200)){
			return R.failed("排除人群定向 最小长度 1，最大长度 200");
		}

		if (targeting.getJSONArray("network_type") != null
				&& (targeting.getJSONArray("network_type").size()< 1 ||
				targeting.getJSONArray("network_type").size()>100)){
			return R.failed("联网方式 最小长度 1，最大长度 100");
		}


		if (targeting.getJSONArray("network_operator") != null
				&& (targeting.getJSONArray("network_operator").size()< 1 ||
				targeting.getJSONArray("network_operator").size()>100)){
			return R.failed("移动运营商 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("network_scene") != null
				&& (targeting.getJSONArray("network_scene").size()< 1 ||
				targeting.getJSONArray("network_scene").size()>100)){
			return R.failed("上网场景 最小长度 1，最大长度 100");
		}
		if (targeting.getJSONArray("dressing_index") != null
				&& (targeting.getJSONArray("dressing_index").size()< 1 ||
				targeting.getJSONArray("dressing_index").size()>100)){
			return R.failed("穿衣指数 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("uv_index") != null
				&& (targeting.getJSONArray("uv_index").size()< 1 ||
				targeting.getJSONArray("uv_index").size()>100)){
			return R.failed("紫外线指数 最小长度 1，最大长度 100");
		}
		if (targeting.getJSONArray("makeup_index") != null
				&& (targeting.getJSONArray("makeup_index").size()< 1 ||
				targeting.getJSONArray("makeup_index").size()>100)){
			return R.failed("化妆指数 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("climate") != null
				&& (targeting.getJSONArray("climate").size()< 1 ||
				targeting.getJSONArray("climate").size()>100)){
			return R.failed("气象 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("consumption_status") != null
				&& (targeting.getJSONArray("consumption_status").size()< 1 ||
				targeting.getJSONArray("consumption_status").size()>100)){
			return R.failed("消费水平 最小长度 1，最大长度 100");
		}

		if (targeting.getJSONArray("game_consumption_level") != null
				&& (targeting.getJSONArray("game_consumption_level").size()< 1 ||
				targeting.getJSONArray("game_consumption_level").size()>2)){
			return R.failed("游戏消费能力 最小长度 1，最大长度 2");
		}

		if (targeting.getJSONArray("financial_situation") != null
				&& (targeting.getJSONArray("financial_situation").size()< 1 ||
				targeting.getJSONArray("financial_situation").size()>2)){
			return R.failed("财产状态 最小长度 1，最大长度 2");
		}

		if (targeting.getJSONArray("consumption_type") != null
				&& (targeting.getJSONArray("consumption_type").size()< 1 ||
				targeting.getJSONArray("consumption_type").size()>2)){
			return R.failed("消费类型 最小长度 1，最大长度 2");
		}

		//地域 校验
		if (targeting.getJSONObject("geo_location") != null){
			JSONObject loc = targeting.getJSONObject("geo_location");
			List<String> types = JSON.parseArray(loc.getString("location_types"), String.class);
			if (types.size() < 1)
				return R.failed("请提供 地点类型");

			int regionLen = loc.getJSONArray("regions") == null ? 0 : loc.getJSONArray("regions").size();
			int busLen = loc.getJSONArray("business_districts") == null ? 0 : loc.getJSONArray("business_districts").size();
			if ((regionLen + busLen) == 0)
				return R.failed("请提供 省市区或商圈");

			if (regionLen > 400)
				return R.failed("地域选项 不能超过400");

			if (busLen > 400)
				return R.failed("商圈选项 不能超过400");

			if (busLen > 0){
				for (String item : types){
					if (!item.equals("LIVE_IN") && !item.equals("VISITED_IN")){
						return R.failed("使用商圈时，位置类型只能选择 常住这里的人/去过这里的人");
					}
				}
			}
		}

		//品牌型号 校验
		JSONObject brand = json.getJSONObject("device_brand_model");
		if (brand != null){
			 JSONArray include = brand.getJSONArray("included_list");
			 JSONArray excluded = brand.getJSONArray("excluded_list");

			 if (include != null && include.size()>400){
			 	return R.failed("设备品牌型号定向 选项不能超过400个");
			 }
			 if (excluded != null && excluded.size() > 400){
				 return R.failed("排除设备品牌型号 选项不能超过400个");
			 }
		}

		//行为兴趣 校验
		JSONObject behaviorInterest = json.getJSONObject("behavior_or_interest");
		if (behaviorInterest != null){
			JSONObject interest = behaviorInterest.getJSONObject("interest");
			JSONArray behavior = behaviorInterest.getJSONArray("behavior");
			JSONObject intention = behaviorInterest.getJSONObject("intention");

			if (interest != null){
				JSONArray cateList = intention.getJSONArray("category_id_list");
				JSONArray keywords = intention.getJSONArray("keyword_list");
				if (cateList != null && (cateList.size() <1 || cateList.size() > 250 ))
					return R.failed("兴趣目录选项 最小长度 1，最大长度 250");
				if (keywords != null && (keywords.size() < 1 || keywords.size()>250))
					return R.failed("兴趣关键词选项 最小长度 1，最大长度 250");

			}

			if (behavior != null){
				if (behavior.size() != 1)
					return R.failed("behavior 数组成都必须为1");
				JSONObject bahObj = behavior.getJSONObject(0);
				if (StringUtils.isBlank(bahObj.getString("time_window")))
					return R.failed("行为定向 必须提供时间窗");

				JSONArray scene = bahObj.getJSONArray("scene");
				JSONArray intensity = bahObj.getJSONArray("intensity");
				JSONArray cateList = bahObj.getJSONArray("category_id_list");
				JSONArray keywords = bahObj.getJSONArray("keyword_list");
				if (cateList != null && (cateList.size() <1 || cateList.size() > 250 ))
					return R.failed("行为目录选项 最小长度 1，最大长度 250");
				if (keywords != null && (keywords.size() < 1 || keywords.size()>250))
					return R.failed("行为关键词选项 最小长度 1，最大长度 250");

				if (scene !=null && scene.size()<1 && scene.size()>3)
					return R.failed("行为定向 最少提供1个场景，最多提供3个");
				if (intensity != null && intensity.size() !=1)
					return R.failed("行为定向 需提供且只能提供1个强度选项");
			}

			if (intention != null){
				JSONArray tags = intention.getJSONArray("targeting_tags");
				if (tags != null && tags.size()<1 && tags.size() > 250)
					return R.failed("行为兴趣-意向选项为1~250个");
			}

		}

		return R.ok("验证通过");
	}

	private String getUrlTail(String accountId){

		//任意去一个 accountId去拿token
		Map<String, String> map = gdtAccesstokenService.fetchAccesstoken(accountId);
		String gdtToken = map.get("access_token");

		//String gdtToken = "4b7eff592ce3abcd4960b378674e6595";

		int nonce = RandomUtils.nextInt();
		long tsp = System.currentTimeMillis() / 1000;
		String tail = String.format("?access_token=%s&timestamp=%d&nonce=%d", gdtToken, tsp, nonce);
		return tail;
	}



	//todo  根据报错信息做相应修改
	private String chineseMsg(String msg){
		for (ToutiaoGdtAudiencePackageFieldsEnum field : ToutiaoGdtAudiencePackageFieldsEnum.values()){
			String replaceStr = field.getType();
			if (msg.contains(replaceStr)){
				msg = msg.replace(replaceStr, String.format(" %s ",field.getName()));
				break;
			}
		}
		msg = msg.replaceAll("trace_id:.*","");
		return msg;
	}

	private static String readFileContent(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sbf.append(tempStr);
			}
			reader.close();
			return sbf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return sbf.toString();
	}


/*	public static void main(String[] args) {
		String test = "测试1";
		System.out.println(getLength(test));
	}*/

	public static int getLength(String str) {
		if (str == null || str.length() == 0) {
			return 0;
		}
		try {
			return str.getBytes("GBK").length;
		} catch (UnsupportedEncodingException e) {
			//
		}
		return 0;
	}


}
